package com.hwua.web.servlet;

import com.alibaba.fastjson.JSON;
import com.hwua.entity.*;
import com.hwua.service.IOrderServcie;
import com.hwua.service.IProductAllService;
import com.hwua.service.IProductService;
import com.hwua.service.IShopCartService;
import com.hwua.service.Impl.OrderServiceImpl;
import com.hwua.service.Impl.ProductAllServiceImpl;
import com.hwua.service.Impl.ProductServiceImpl;
import com.hwua.service.Impl.ShopCartServiceImpl;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.*;

@WebServlet("/shopCarts")
public class ShoppingCartServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("application/json;charset=utf-8");
        HttpSession session = request.getSession(false);
        String param = request.getParameter("param");
        IShopCartService shopCartService=new ShopCartServiceImpl();//?
        IOrderServcie orderServcie = new OrderServiceImpl();
        IProductService productService = new ProductServiceImpl();
        IProductAllService productAllService1=new ProductAllServiceImpl();
        User user=(User)session.getAttribute("user");
        ShopCart shopCart=new ShopCart();
        Map<String,Object> map=new HashMap<>();
        if(param.equals("shopItem")) {
            Product product = (Product) session.getAttribute("NOHA");
            IProductAllService productAllService = new ProductAllServiceImpl();
        }
        if(param.equals("addShopItem")){
            Product product = (Product) session.getAttribute("pro");
            System.out.println(product);
            String count = request.getParameter("count");//商品数量
            /*request.setAttribute("product", product);
            request.setAttribute("count", Integer.getInteger(count));*///?是否需要string转int
            product.getMinor_id();//TWo number;
            List<ShopCart>shopCarta = null;
            try {
                shopCarta = shopCartService.queryShopCartBypid((int) product.getId());
            } catch (SQLException e) {
                e.printStackTrace();
            }
            if(shopCarta.size()!=0){
                       ShopCart shopCart1 = shopCarta.get(0);
                       shopCart1.setPnum(shopCart1.getPnum()+Integer.parseInt(count));
                try {
                    int i=shopCartService.updateShoItem(shopCart1);
                    if(i>0){
                        map.put("success",true);
                        map.put("info","加入购物车成功");
                    }else{
                        map.put("success",false);
                        map.put("info","加入购物车失败");
                    }
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }else {
                shopCart.setPid(product.getId());
                shopCart.setPnum(Integer.parseInt(count));
                try {
                    if(user==null){
                        shopCart.setUid(0);
                    }else{
                        shopCart.setUid(user.getId());
                    }
                    int i = shopCartService.insertShoItem(shopCart);
                    if(i>0){
                        map.put("success",true);
                        map.put("info","加入购物车成功");
                    }else{
                        map.put("success",false);
                        map.put("info","加入购物车失败");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }



            response.getWriter().write(JSON.toJSONString(map));
//            request.getRequestDispatcher("/product?param=shopCarts").forward(request,response);
           /* String ShopCartId = linkId(String.valueOf(product.getId()), request);//获取拼好的商品id,格式:1-2-3-4
            Cookie cookie = new Cookie("ShopCartId", ShopCartId);
            response.addCookie(cookie);
            request.getRequestDispatcher("/product_view.jsp").forward(request, response);*/
        }else if(param.equals("del")){
            String id = request.getParameter("id");
            try {
                shopCartService.delShopCart(Integer.parseInt(id));
            } catch (Exception e) {
                e.printStackTrace();
            }
            request.getRequestDispatcher("/product?param=shopCarItem").forward(request,response);
        }else if(param.equals("payment")){
           // String count = request.getParameter("count");
            //System.out.println(count);
            if(user!=null){
            try {
                List<ProductExtend> product = shopCartService.queryShopCartByuid(user.getId());
                for(ProductExtend productExtend:product){
                    Order order=new Order();
                    Date date = new Date();
                    SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
                    String dateString = simpleDateFormat.format(date);
                    order.setCreatetime(dateString);
                    order.setMoney(productExtend.getCount()*productExtend.getPrice());
                    order.setStatus(1);
                    order.setType(1);
                    order.setUid(user.getId());
                    order.setUname(user.getUname());
                    order.setUaddress(user.getAddress());
                    orderServcie.insertOrder(order);
                  //  shopCartService.delShopCart((int) productExtend.getId());
                }
            } catch (Exception e) {
                e.printStackTrace();
            }


            request.getRequestDispatcher("/shopping-result.jsp").forward(request,response);}
            else {
                    List<NewOrderInfo> newOrderInfos = new ArrayList<>();
                    List<ProductExtend> product = null;
                    try {
                        product = shopCartService.queryShopCartByuid(0);
                        Cookie cookie = new Cookie("productcart",JSON.toJSONString(product));
                        response.addCookie(cookie);
                        request.getRequestDispatcher("/login.jsp").forward(request, response);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
        }else if(param.equals("neworderinfo")) {
                List<NewOrderInfo> newOrderInfos = new ArrayList<>();
                List<ProductExtend> product = null;
                try {
                    product = shopCartService.queryShopCartByuid(user.getId());
                } catch (Exception e) {
                    e.printStackTrace();
                }

                try {
                    List<Order> orders = orderServcie.selectByUid(user.getId());
                    for (int i = 0; i < product.size(); i++) {
                        NewOrderInfo newOrderInfo = new NewOrderInfo();
                        Order order = orders.get(i);
                        ProductExtend product1 = product.get(i);
                        List<ShopCart> ShopCarts = shopCartService.queryShopCartBypid((int) product1.getId());
                        ShopCart shopCart2 = null;
                        for (ShopCart shopCart1 : ShopCarts) {
                            if (shopCart1.getUid() == user.getId()) {
                                shopCart2 = shopCart1;
                            }
                        }
                        newOrderInfo.setTitle(product1.getName());
                        newOrderInfo.setImageurl(product1.getImg_source());
                        newOrderInfo.setOrdernum(String.valueOf(order.getId()));
                        newOrderInfo.setOrdertime(order.getCreatetime());
                        newOrderInfo.setTotal((float) (shopCart2.getPnum() * product1.getPrice()));
                        newOrderInfo.setNum((int) shopCart2.getPnum());
                        newOrderInfo.setPrice((float) product1.getPrice());
                        newOrderInfo.setPid((int) product1.getId());
                        // Product product = productAllService1.queryById();
                        newOrderInfos.add(newOrderInfo);
                    }
                    request.setAttribute("newordersinfo", newOrderInfos);
                    // List<ProductExtend> product = shopCartService.queryShopCartByuid(user.getId());
                    for (ProductExtend productExtend : product) {
                        // orderServcie.insertOrder(order);
                        shopCartService.delShopCart((int) productExtend.getId());
                    }
                } catch (SQLException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                request.getRequestDispatcher("/orders_view.jsp").forward(request, response);
            }
        }

    //拼接方法(拼接的逻辑都写在这里)
    private String linkId(String id, HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();
        String histroyId = null;
        boolean flag = false;//默认没有找到指定名字的cookie
        //非第一次访问的时候
        if (cookies != null && cookies.length > 0) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals("histroyId")) {
                    flag = true;
                    histroyId = cookie.getValue();//1-2-3
                    break;
                }
            }
        }

        //浏览第一个商品的时候
        if (cookies == null || flag == false) {
            histroyId = id;
        }

        LinkedList<String> list = new LinkedList<String>(Arrays.asList(histroyId.split("-")));
        //假如长度不满4,冲突:先删除冲突的id,再把id添加到头部,不冲突,直接放到头部

        if (list.size() < 4) {
            if (list.contains(id)) {
                list.remove(id);//先删除
            }
        }

        if (list.size() == 4) {
            if (list.contains(id) == false) {
                list.removeLast();// 删除最后一个id
            } else {
                list.remove(id);//先删除
            }
        }
        list.addFirst(id);//添加到头部
        //动态拼接id
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < list.size(); i++) {
            if (i > 0) {
                sb.append("-");
            }
            sb.append(list.get(i));//拼接字符串
        }
        return sb.toString();
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
